package org.example.task.model.query;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.validation.constraints.NotNull;
import lombok.Data;

/**
 * 分页查询实体类
 */
@Data
public class PageQuery {
    /**
     * 页码
     */
    @NotNull
    private  Long page;
    /**
     * 每页数据条数
     */
    @NotNull
    private  Long pageSize;
    /**
     * 排序字段
     */
    private String sortBy;
    /**
     * 是否升序
     */
    private boolean isAsc;

    public <T> Page<T> toPage(OrderItem ... orderItems) {

        Page<T> p = new Page<>();
        p.setCurrent(this.page);
        p.setSize(this.pageSize);
        //先看看前端有没有传排序字段
        if (this.sortBy != null) {
            OrderItem orderItem = new OrderItem();
            orderItem.setAsc(this.isAsc);
            orderItem.setColumn(this.sortBy);
            p.addOrder(orderItem);
            return p;
        }
        //再看看有没有手动指定排序字段
        if (orderItems != null && orderItems.length > 0) {
            p.addOrder(orderItems);
        }
        return p;
    }

    /**
     * 默认字段的排序
     * @param defaultSortBy 默认字段
     * @param isAsc 是否升序
     * @return 分页结果
     * @param <T> 泛型
     */
    public <T> Page<T> toPage(String defaultSortBy, boolean isAsc){
        OrderItem orderItem = new OrderItem();
        orderItem.setAsc(isAsc);
        orderItem.setColumn(defaultSortBy);
        return this.toPage(orderItem);
    }
    public <T> Page<T> toPageDefaultSortByCreateTimeDesc(){
        OrderItem orderItem = new OrderItem();
        orderItem.setAsc(false);
        orderItem.setColumn("create_time");
        return this.toPage(orderItem);
    }
    public <T> Page<T> toPageDefaultSortByUpdateTimeDesc(){
        OrderItem orderItem = new OrderItem();
        orderItem.setAsc(false);
        orderItem.setColumn("update_time");
        return this.toPage(orderItem);
    }
}
